package projects

import (
	"github.com/beego/beego/v2/client/orm"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
	"xpms/app/models"
	"xpms/cores"
	"xpms/cores/utils"
)

type ProjectsTeam struct {
	Id        int64 `orm:"pk;" json:"Id,string"`
	Projectid int64 `json:"Projectid,string"`
	Userid    int64 `json:"Userid,string"`
	Role      int   `json:"Role,string"`
	Created   int64
}

func (this *ProjectsTeam) TableName() string {
	return models.TableName("projects_team")
}
func init() {
	orm.RegisterModel(new(ProjectsTeam))
}

func AddTeam(upd ProjectsTeam) error {
	o := orm.NewOrm()
	team := new(ProjectsTeam)
	team.Id = upd.Id
	team.Projectid = upd.Projectid
	team.Userid = upd.Userid
	team.Created = time.Now().Unix()
	_, err := o.Insert(team)
	return err
}

/**
  批量添加
*/
func AddMultiTeam(upd []ProjectsTeam) error {
	o := orm.NewOrm()
	_, err := o.InsertMulti(100, upd)
	return err
}

type TeamUserName struct {
	Userid   int64 `json:"Userid,string"`
	Realname string
}

func DeleteProjectTeam(id int64) error {
	o := orm.NewOrm()
	_, err := o.Delete(&ProjectsTeam{Id: id})
	return err
}

func GetProjectTeam(userid, projectid int64) (ProjectsTeam, error) {
	var team ProjectsTeam
	o := orm.NewOrm()
	qs := o.QueryTable(models.TableName("projects_team"))
	err := qs.Filter("userid", userid).Filter("projectid", projectid).One(&team)
	if err == orm.ErrNoRows {
		return team, nil
	}
	return team, err
}

type ProjectsTeamDto struct {
	Id            int64 `json:"Id,string"`
	Projectid     int64 `json:"Projectid,string"`
	Projectname   string
	Userid        int64 `json:"Userid,string"`
	Userrealname  string
	Created       int64
	Role          int `json:"Role,string"`
	Positionsname string
	Depatname     string
	Departid      string
	Positionid    string
}

func TeamPageExec(condArr map[string]interface{}, page int, offset int) (ops []ProjectsTeamDto) {
	o := orm.NewOrm()
	var dto []ProjectsTeamDto
	o.Raw(teamPageSql(condArr, 1, page, offset)).QueryRows(&dto)
	return dto
}

func TeamPageCountExec(condArr map[string]interface{}, page int, offset int) int64 {
	o := orm.NewOrm()
	var contDto int64
	o.Raw(teamPageSql(condArr, 0, page, offset)).QueryRow(&contDto)
	return contDto
}

/**
  组装sql
*/
func teamPageSql(condArr map[string]interface{}, ifsCount, page int, offset int) (string, []interface{}) {
	var sql string
	if ifsCount == 0 {
		sql = sql + `SELECT count(1) FROM (`
	}
	sql = sql + `
	SELECT
	  ppt.*,
	  pp.name AS projectname,
	  up.realname AS userrealname,
      pos.positionid  AS positionid,
      pos.name  AS positionsname,
      depat.departid AS departid,
      depat.name AS depatname
	FROM  pms_projects pp
	  LEFT JOIN pms_projects_team ppt 
		ON ppt.projectid = pp.projectid
	  INNER JOIN pms_users_profile up ON up.userid=ppt.userid
    LEFT JOIN pms_positions pos ON up.positionid=pos.positionid
    LEFT JOIN pms_departs depat ON depat.departid=up.departid
	WHERE 1 = 1 `
	param := make([]interface{}, 0, 0)
	if !utils.IsEmpty(condArr["projectid"]) {
		sql = sql + ` and  pp.projectid=?`
		param = append(param, condArr["projectid"])
	}
	if !utils.IsEmpty(condArr["keyword"]) {
		sql = sql + ` and  up.realname LIKE concat('%',?,'%')`
		param = append(param, condArr["keyword"])
	}
	if ifsCount == 0 {
		sql = sql + ` ) C`
	} else if ifsCount > 0 {
		if page < 1 {
			page = 1
		}
		if offset < 1 {
			offset, _ = beego.AppConfig.Int("pageoffset")
		}
		start := (page - 1) * offset
		startStr := strconv.Itoa(start)
		offsetStr := strconv.Itoa(offset)
		sql = sql + ` order by created desc LIMIT ` + startStr + `,` + offsetStr
	}
	return sql, param
}

func DeleteTeam(ids []string) error {
	o := orm.NewOrm()
	sql := `
	DELETE FROM pms_projects_team 
	WHERE `
	param := make([]interface{}, 0, 0)
	if !utils.IsEmpty(ids) {
		sql = sql + ` id in(`
		sql1, value := cores.SqlInParam(ids)
		sql = sql + sql1 + `)`
		param = append(param, value...)
	}
	_, err := o.Raw(sql, param).Exec()
	return err
}
